Strings


In [27]:
# Below are two ways to get the last character in a string
# Also known as getting the last letter in a word
#        012345678
fruit = 'cranberry'

# Long way
number_of_characters_in_fruit = len(fruit)
last_item_location = number_of_characters_in_fruit - 1
lastch = fruit[last_item_location]

print('Number of characters: ', number_of_characters_in_fruit)
print(lastch)

# Short way
lastch = fruit[-1]

new_fruit = fruit[:2]
second_new_fruit = fruit[:-4]
print('New fruit:', new_fruit)
print('Second fruit:', second_new_fruit)
print('Last char of fruit:', lastch)
print(fruit[1])
print(fruit[5])
print(fruit[number_of_characters_in_fruit])


Number of characters:  9
y
New fruit: cr
Second fruit: cranb
Last char of fruit: y
r
e
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-27-cb04b8838d31> in <module>()
     22 print(fruit[1])
     23 print(fruit[5])
---> 24 print(fruit[number_of_characters_in_fruit])

IndexError: string index out of range

String Comparison

Don't compare strings without normalizing them first.

For example don't compare "How" to "MeoW" compare "how" to "meow"


In [50]:
import random

def determine_character(character):
    if 1 == random.randint(0,1):
        return character
    return ''


name = 'GaRrY PolLEy'
new_name = ''
for character in name:
    new_name = new_name + determine_character(character)
    print(character, ':', ord(character))

print(ord('A'))
print(ord('a'))
print(new_name)


G : 71
a : 97
R : 82
r : 114
Y : 89
  : 32
P : 80
o : 111
l : 108
L : 76
E : 69
y : 121
65
97
aY P

In [36]:
first_word = input("What is the first word: ")
second_word = input("What is the second word: ")

# Exmaple text that needs normalized
what_street = 'Maple Street'
another_street = 'maple street'

normalized_first_word = first_word.lower()
normalized_second_word = second_word.lower()

print(normalized_first_word, ':', normalized_second_word)

# Boolean assignment
are_words_the_same = normalized_first_word == normalized_second_word
print("The strings are the same once normalized?", are_words_the_same)


What is the first word: Apple
What is the second word: APPLE
apple : apple
The strings are the same once normalized? True

Immutable


In [45]:
set_of_values = [1,2,3,4]
print(set_of_values)
set_of_values[0] = 'meow cats'
print(set_of_values)

string_cannot_change = 'I am not changable'
print(string_cannot_change)

string_cannot_change = 10
print(string_cannot_change)

string_cannot_change = 'é'
print(string_cannot_change)

string_cannot_change = 'A different string is okay, but why?'
print(string_cannot_change)

string_cannot_change[7] = 'T'
string_cannot_change[7] = 'This will error'


[1, 2, 3, 4]
['meow cats', 2, 3, 4]
I am not changable
10
é
A different string is okay, but why?
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-45-ce4224ab807d> in <module>()
     16 print(string_cannot_change)
     17 
---> 18 string_cannot_change[7] = 'T'
     19 string_cannot_change[7] = 'This will error'

TypeError: 'str' object does not support item assignment

In [51]:
# Cheating answer
def is_sorted(string):
    """Returns True if string is sorted from least to greatest
       False otherwise.
    """
    return ''.join(sorted(string)) == string


print('value', is_sorted('value'))
print('abc', is_sorted('abc'))
print('aBc', is_sorted('aBc'))


value False
abc True
aBc False

In [54]:
def is_sorted(string):
    for i in range(1, len(string)):

        previous_location = i - 1
        if string[previous_location] > string[i]:
            return False

    return True

print(is_sorted('ABC'))
print(is_sorted('BBC'))
print(is_sorted('CBC'))
print(is_sorted('CBS'))
print(is_sorted('NBC'))
print(is_sorted('aBc'))
print('a', ord('a'), 'B', ord('B'))


True
True
False
False
False
False
a 97 B 66

In [73]:
def is_sorted(string):
    n = 1

    for char in string:

        if char <= string[n]:
            n = n + 1
            
            if n == len(string):
                return True
        else:
            return False
    
    return False

print(is_sorted('ABC'))
print(is_sorted('BBC'))
print(is_sorted('CBC'))
print(is_sorted('CBS'))
print(is_sorted('NBC'))
print(is_sorted('aBc'))


True
True
False
False
False
False

In [78]:
def is_valid_password(string):
   upper_check = False
   lower_check = False
   char_check = False
   char_list = "!@#$%^&*()-_+"

   for char in string:

       if (ord(char) >= 65) and (ord(char) <= 90):
           upper_check = True

       if (ord(char) >= 97) and (ord(char) <= 122):
           lower_check = True

       if char in char_list:
           char_check = True

   return upper_check and lower_check and char_check and len(string) > 12

print(chr(65), chr(90), chr(97), chr(122))
is_valid_password('$aAjfasdfasdfasdfasdf')


A Z a z
Out[78]:
True

In [ ]: